import { useStreams } from '@/lib/utils'
import services from '@/services'

export function SocketStatus() {
  const [status] = useStreams(services.mqtt.status)

  const [waitingSecs, setWaitingSecs] = useState(0) // status=connecting|reconnecting 时有效，已等待连接成功或重连多少秒
  useEffect(() => {
    if (status === 'connecting' || status === 'reconnecting') {
      let seconds = 0
      const intervalId = setInterval(() => setWaitingSecs(++seconds), 1000)
      return () => {
        clearInterval(intervalId)
        setWaitingSecs(0)
      }
    }
  }, [status])

  return <div css={styles.status}>
    {status === 'connecting' ? (
      <div className="warn">网络连接中... {waitingSecs ? ` ${waitingSecs}s` : ''}</div>
    ) : null}
    {status === 'reconnecting' ? (
      <div className="warn">网络重连中... {waitingSecs ? ` ${waitingSecs}s` : ''}</div>
    ) : null}
    {status === 'connectFailed' ? <div className="error">网络连接失败</div> : null}
  </div>
}

const styles = {
  status: css`
    color: rgba(85, 85, 85, 0.65);
    font-size: 12px;
    margin-left: 20px;

    & > div {
      &:before {
        border-radius: 10px;
        content: ' ';
        display: inline-block;
        height: 8px;
        margin-right: 6px;
        width: 8px;
      }
      &.warn:before {
        background-color: #ffa515;
      }
      &.error:before {
        background-color: #ff4868;
      }
    }
  `,
}
